package com.zhongshengnetwork.rightbe.commentstore.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.FragmentViewPageAdapter;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreClassifyModel;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreModel;
import com.zhongshengnetwork.rightbe.commentstore.view.CommentStoreClassifyFragment;
import com.zhongshengnetwork.rightbe.commentstore.view.CommentStoreFragment;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.KeyMapDailog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.huantansheng.easyphotos.constant.Code.REQUEST_PERMISSION;
import static com.zhongshengnetwork.rightbe.common.customview.KeyMapDailog.TextKey;

public class CommentHomeActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener, View.OnClickListener{//BaseFragmentActivity

    public static final int CLASSIFY_PUBLISH = 1001;
    public static final int CLASSIFY_INFO = 1002;

    private TopBarView topbar;
    private TextView text1, text2,text3;
    private ImageView tabLine;
    private ViewPager pager;
    private DisplayMetrics dm = new DisplayMetrics();
    private int tabWidth;
    private List<Fragment> fragments;

    private CommentStoreFragment commentStoreFragment;
    private CommentStoreFragment oftenCommentStore;
    private CommentStoreClassifyFragment commentStoreClassifyFragment;

    //图片浏览
    public ImageViewer imagePreivew;
    //加载动画
    private AVLoadingIndicatorView avi;

    public LangInfoModel langInfoModel;

    //评论弹出框
    private KeyMapDailog dialog = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CLASSIFY_PUBLISH && resultCode == RESULT_OK){
            pager.setCurrentItem(0);
            commentStoreFragment.getFirstData(false);
        }else if (requestCode == CLASSIFY_INFO && resultCode == RESULT_OK){
            pager.setCurrentItem(2);
            commentStoreClassifyFragment.getFirstData(false);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_home);

        langInfoModel = (LangInfoModel) getIntent().getSerializableExtra("model");

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);

        topbar.getRightView().setImageResource(R.drawable.whiteadd);
        topbar.getRightView().setVisibility(View.VISIBLE);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                        && ContextCompat.checkSelfPermission(CommentHomeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(CommentHomeActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                            REQUEST_PERMISSION);
//                    ToastUtil.show(CommentHomeActivity.this,"亲，请开启应用对SD卡的读写权限");
//                    return;
//                }
                showMenu();
            }
        });

        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        topbar.getTitleView().setClickable(true);
        topbar.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fragments != null && fragments.size() > 0){
                    if (pager.getCurrentItem() == 0){
                        commentStoreFragment.getFirstData(true);
                    }else if (pager.getCurrentItem() == 1){
                        oftenCommentStore.getFirstData(true);
                    }else if (pager.getCurrentItem() == 2){
                        commentStoreClassifyFragment.getFirstData(true);
                    }
                }
            }
        });
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        tabWidth = dm.widthPixels / 3;
        fragments = new ArrayList<Fragment>();
        initView();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void showMenu(){
        final List<String> menu = new ArrayList<>();
        menu.add("提交一次性评论");
        menu.add("新增评论");
        menu.add("新建评论库");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(CommentHomeActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : menu){
             actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                 @Override
                 public void onClick(int which) {
                     if (which > 0){
                         which -= 1;
                         String title = menu.get(which);
                         if (title.equals("新增评论")){
                             addComment();
                         }else if (title.equals("新建评论库")){
                             addCommentStore();
                         }else if(title.equals("提交一次性评论")){
                             CommentStoreModel m = new CommentStoreModel();
                             m.setContent("");
                             m.setClassifyId(0);
                             m.setCommentId(0L);
                             showComment(m);
                         }
                     }
                 }
             });
        }
        actionSheetDialog.show();
    }

    public void addComment(){
        Intent intent = new Intent(CommentHomeActivity.this, NewCommentStoreActivity.class);
        startActivityForResult(intent, CLASSIFY_PUBLISH);
    }

    public void editComment(CommentStoreModel model){
        Intent intent = new Intent(CommentHomeActivity.this, NewCommentStoreActivity.class);
        Bundle bundle=new Bundle();
        bundle.putSerializable("model", model);//序列化
        intent.putExtras(bundle);//发送数据
        startActivityForResult(intent, CLASSIFY_PUBLISH);
    }

    public void addCommentStore(){
        Intent intent = new Intent(CommentHomeActivity.this, NewCommentStoreClassifyActivity.class);
        startActivityForResult(intent, CLASSIFY_INFO);
    }

    private void showComment(final CommentStoreModel model){
        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(TextKey, model.getContent());
        if (CommonUtils.bindMobile(CommentHomeActivity.this) == true){
            return;
        }
        dialog = new KeyMapDailog("提交一次性评论...", new KeyMapDailog.SendBackListener() {
            @Override
            public void sendBack(final String inputText) {
                if (inputText == null || inputText.length() == 0){
                    return;
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //dialog.hideProgressdialog();
                        dialog.dismiss();
                        new Thread(){
                            @Override
                            public void run() {
                                super.run();
                                final HashMap<String, String> map = new HashMap<String, String>();
                                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                                map.put("dataContent",inputText);
                                map.put("dataId",""+model.getCommentId());
                                map.put("dataSourceId",langInfoModel.getLangid());
                                String url = "comment/store/content/commit.do";
                                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                                    @Override
                                    public void onSuccess(String data) {
                                        Log.e("TAG","评论结果："+data);
                                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                                        if (commonModel.getFlag().equals("1")){
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    avi.hide();
                                                    ToastUtil.show(CommentHomeActivity.this, "提交成功");

                                                }
                                            });
                                        }else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    avi.hide();
                                                    ToastUtil.show(CommentHomeActivity.this, commonModel.getMsg());
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void onError(String msg) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                avi.hide();
                                                ToastUtil.show(CommentHomeActivity.this, "提交失败");
                                            }
                                        });
                                    }
                                });
                            }
                        }.start();
                    }
                }, 5);
            }
        });
        dialog.show(getSupportFragmentManager(), "dialog");
    }

    private void initView() {
        text1 = (TextView) findViewById(R.id.text1);
        text1.setOnClickListener(this);
        text2 = (TextView) findViewById(R.id.text2);
        text2.setOnClickListener(this);
        text3 = (TextView) findViewById(R.id.text3);
        text3.setOnClickListener(this);
        tabLine = (ImageView) findViewById(R.id.tabLine);
        pager = (ViewPager) findViewById(R.id.pager);

        text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        commentStoreFragment = new CommentStoreFragment();
        commentStoreFragment.dataType = "0";
        commentStoreFragment.commentHomeActivity = CommentHomeActivity.this;
        fragments.add(commentStoreFragment);

        oftenCommentStore = new CommentStoreFragment();
        oftenCommentStore.dataType = "2";
        oftenCommentStore.commentHomeActivity = CommentHomeActivity.this;
        fragments.add(oftenCommentStore);

        commentStoreClassifyFragment = new CommentStoreClassifyFragment();
        if (langInfoModel != null){
            commentStoreClassifyFragment.sourceId = langInfoModel.getLangid();
        }
        commentStoreClassifyFragment.commentHomeActivity = CommentHomeActivity.this;
        fragments.add(commentStoreClassifyFragment);

        /**
         * 这里Activity 只有继承 FragmentActivity 的时候 ，才会 getSupportFragmentManager()
         */
        // 设置适配器
        FragmentViewPageAdapter fragmentViewPageAdapter = new FragmentViewPageAdapter(
                getSupportFragmentManager(), fragments);
        pager.setAdapter(fragmentViewPageAdapter);
        pager.setOnPageChangeListener(new PageListener());

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.tab_line);
        int w = tabWidth;
        if (bitmap.getWidth()<tabWidth){
            //w = bitmap.getWidth();
        }
        int h = 4;
        if (bitmap.getHeight() < h){
            h = bitmap.getHeight();
        }
        Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, w, h);// 设置tab的宽度和高度
        tabLine.setImageBitmap(b);

        RelativeLayout activity_user_layout = (RelativeLayout) findViewById(R.id.comment_layout);
        activity_user_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        pager.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text1:
                pager.setCurrentItem(0);
                break;
            case R.id.text2:
                pager.setCurrentItem(1);
                break;
            case R.id.text3:
                pager.setCurrentItem(2);
                break;
            default:
                break;
        }
    }

    /**
     * 监听
     */
    public class PageListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            Matrix matrix = new Matrix();
            // 设置激活条的最终位置
            switch (arg0) {
                case 0:
                    // 使用set直接设置到那个位置
                    matrix.setTranslate(0, 0);
                    break;
                case 1:
                    matrix.setTranslate(tabWidth, 0);
                    break;
                case 2:
                    matrix.setTranslate(tabWidth*2, 0);
                    break;
            }
            // 在滑动的过程中，计算出激活条应该要滑动的距离
            float t = (tabWidth) * arg1;
            // 使用post追加数值
            matrix.postTranslate(t, 0);
            tabLine.setImageMatrix(matrix);
        }

        @Override
        public void onPageSelected(int arg0) {
            text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            switch (arg0) {
                case 0:
                    text1.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 1:
                    text2.setTextColor(Color.parseColor("#ff008000"));
                    break;
                case 2:
                    text3.setTextColor(Color.parseColor("#ff008000"));
                    break;
                default:
                    break;
            }
        }
    }

}
